package org.oos.auth;

import java.io.IOException;
import java.util.List;

import org.oos.atom.AtomService.HttpStatusException;
import org.oos.dao.options.OptionsMap;

import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;

public class OAuthAuthentication extends AbstractAuthentication {

	private String consumerKey;

	private String accessToken;

	private OAuthParameters authorizer;

	public String getConsumerKey() {
		return consumerKey;
	}

	public String getAccessToken() {
		return accessToken;
	}

	public OAuthAuthentication(String consumerKey, String consumerSecret,
			String accessToken, String tokenSecret) {
		this.consumerKey = consumerKey;
		this.accessToken = accessToken;

		// Signer
		OAuthHmacSigner signer = new OAuthHmacSigner();
		signer.clientSharedSecret = consumerSecret;
		signer.tokenSharedSecret = tokenSecret;

		// Authorizer
		this.authorizer = new OAuthParameters();
		authorizer.consumerKey = consumerKey;
		authorizer.token = accessToken;
		authorizer.signer = signer;
	}

	private void signTransport(HttpTransport transport) {
		authorizer.signRequestsUsingAuthorizationHeader(transport);
	}

	@Override
	public HttpResponse getResponse(HttpTransport transport, GenericUrl url,
			String method, HttpContent content, List<OptionsMap> parameters)
			throws IOException, HttpStatusException {
		try {
			signTransport(transport);
			HttpRequest request = transport.buildRequest();
			request.method = method;
			request.url = pack(url, parameters);
			request.content = content;
			HttpResponse response = request.execute();
			return response;
		} catch (HttpResponseException e) {
			HttpStatusException exception = new HttpStatusException(e.response.statusCode, "URL: " + url + " - " + e.getMessage());
			exception.setResponse(e.response);
			throw exception;
		}
	}

	@Override
	public boolean isAnonymous() {
		return false;
	}

}
